package pers.cz.postgirl.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @program: postgirl-client
 * @description: 对象工具
 * @author: Cheng Zhi
 * @create: 2023-07-31 14:08
 **/
public class ObjUtils {

    private static JefLog jefLog = new JefLog(ObjUtils.class);

    /**
     * 获取一个Collection对象的泛型类
     * @param obj
     * @return
     */
    public static Class getGenericsClass(Object obj) {

        String typeName = getGenericsTypeName(obj);
        Class<?> aClass = null;
        try {
            aClass = Class.forName(typeName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return aClass;
    }

    /**
     * 获取指定类全名的Class对象
     * @param typeName
     * @return
     */
    public static Class getClass(String typeName) {

        Class<?> aClass = null;
        try {
            aClass = Class.forName(typeName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return aClass;
    }

    public static String getGenericsTypeName(Object obj) {

        String typeName = "";
        try {
            Type clazz = obj.getClass().getGenericSuperclass();
            if (clazz instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType)clazz;
                Type actualTypeArgument = pt.getActualTypeArguments()[0];
                typeName = actualTypeArgument.getTypeName();
                jefLog.debug("获取到的泛型类：" + typeName);
            }
        } catch (Exception exceptin) {
            jefLog.error("获取泛型失败，或许是没有泛型：" + obj.getClass().getName());
        }

        return typeName;
    }
}
